//
//  TalkfunTools.m
//  TalkfunMediaPlayerDemo
//
//  Created by LuoLiuyou on 16/7/5.
//  Copyright © 2016年 luoliuyou. All rights reserved.
//
#import "TalkfunUtils.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <sys/sysctl.h>
#import <net/if.h>
#import <net/if_dl.h>
#import <CoreText/CoreText.h>
#import <WebKit/WebKit.h>
#import <Foundation/Foundation.h>
#define BEGIN_FLAG @"["
#define END_FLAG @"]"
#define KFacialSizeHeight 18
#define KFacialSizeWidth  18
#define MAX_WIDTH [TalkfunUtils getMainScreen].size.width - 40
#define UIColorFromRGBHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define LIGHTBLUECOLOR UIColorFromRGBHex(0x93a9d1)
typedef NS_ENUM(NSInteger, TF_Directory) {
    TF_DirectoryDocuments     = 0,
    TF_DirectoryLibrary      = 1,
    TF_DirectoryTemp         = 2,
};
//=========== 方法名 ================
#define AttributeStr @"attributeStr"
#define TextRect @"textRect"
#define  internalBackgroundColor [UIColor colorWithRed:255/255.0 green:162/255.0 blue:0/255.0 alpha:1.0]
@interface TalkfunUtils()
@property(nonatomic,strong)WKWebView *wkWebView;
@property(nonatomic,strong)NSString * user_Agent ;
@end
static TalkfunUtils *_counter;
@implementation TalkfunUtils

+ (NSString *)md5:(NSString *)string
{
    const char *cStr = [string UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (int)strlen(cStr), result);
    return [[NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]] lowercaseString];
}

+ (NSString*)getMd5_32Bit_Data:(NSData*)data
{
    
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5((data.bytes),(CC_LONG)(data.length) ,digest);
    
    NSMutableString*result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}

+ (NSInteger)getTimestamp
{
    return (NSInteger)[[NSDate date] timeIntervalSince1970];
}
+ (NSMutableAttributedString *)getUserNameAndTimeWith:(NSDictionary *)params playback:(BOOL)playback
{
    if (playback) {
        NSString * userName  = params[@"nickname"];
        NSString * starttime = params[@"time"];
        if (!starttime) {
            starttime = params[@"startTime"];
        }
        NSInteger time       = [starttime integerValue];
        NSInteger hour       = time / 3600;
        NSInteger minutes    = (time - hour * 3600) / 60;
        NSInteger second     = time - minutes * 60 - hour * 3600;

        if (hour==00) {
            return [TalkfunUtils getAttributeNameStr:[NSString stringWithFormat:@"%@ %02ld:%02ld",userName,(long)minutes,(long)second] range:NSMakeRange(0, userName.length)];
        }else{
            return [TalkfunUtils getAttributeNameStr:[NSString stringWithFormat:@"%@ %02ld:%02ld:%02ld",userName,(long)hour,(long)minutes,(long)second] range:NSMakeRange(0, userName.length)];
        }
        
        

    }else{
        NSString * userName = params[@"nickname"];
        NSString * time     = params[@"time"];
        if (params[@"amount"]) {
            return [TalkfunUtils getAttributeNameStr:[NSString stringWithFormat:@"%@:(%@)",userName,time]range:NSMakeRange(0, userName.length)];
        }
        NSTimeInterval timeInterval    = [time doubleValue];
        NSDate *detaildate             = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; // 固定格式解析
        dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];     // 指定为北京时间
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"HH:mm"];
        
        NSString * currentDateStr      = [dateFormatter stringFromDate: detaildate];
        
    
        return [TalkfunUtils getAttributeNameStr:[NSString stringWithFormat:@"%@ %@",userName?userName:@"",currentDateStr?currentDateStr:@""]range:NSMakeRange(0, userName.length)] ;
    }
}

//获取手机UUID
+ (NSString *)UUID
{
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
+(NSMutableAttributedString*)getAttributeNameStr:(NSString*)str  range:(NSRange)range
{
    
     NSMutableAttributedString *fontAttributeNameStr = [[NSMutableAttributedString alloc]initWithString:str];
    
    
    if (range.length<fontAttributeNameStr.length) {
        //名字
        [fontAttributeNameStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:range];
        
        [fontAttributeNameStr addAttribute:NSForegroundColorAttributeName value:LIGHTBLUECOLOR range:range];
        
        
        
        //时间
        [fontAttributeNameStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(range.length, str.length - range.length)];
        //设置颜色
        [fontAttributeNameStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(range.length, str.length - range.length)];
        
    }
   
    
    return fontAttributeNameStr;
}
+ (NSString *)urlencode: (NSString *) input
{
    if([input isKindOfClass:[NSString class] ]){
        NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                                        NULL,
                                                                                                        (__bridge CFStringRef) input,
                                                                                                        NULL,
                                                                                                        CFSTR("!*'();:@&=+$,/?%#[]\" "),
                                                                                                        kCFStringEncodingUTF8));
        
        return escapedString;
    }
    return input;
}


+ (NSString *)jsonEncode:(NSObject *)input {

    return [self dictionarySerializer:input];

}
+ (NSString *)dictionarySerializer:(NSObject *)dict {
    NSObject *obj = nil;
    if ([dict isKindOfClass:[NSDictionary class]]) {
        obj =  [self dictShowAllFile:(NSDictionary*)dict];
    }
   else if ([dict isKindOfClass:[NSArray class]]) {
        obj =  [self ayyayShowAllFile:(NSArray*)dict];
    }else if ([dict isKindOfClass:[NSString class]]) {
        return (NSString*)dict;
    }else {
        return @"";
    }
    NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    NSString *temp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
   
    return temp;
}
+ (NSMutableDictionary*)dictShowAllFile:(NSDictionary *)dict {
    
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    
    for (int i = 0; i < dict.count; ++i) {
   //  获取字典中所有的key
    NSArray *keys = [dict allKeys];
   //  取出当前位置对应的key
    NSString *key = keys[i];
    NSObject *value = dict[key];

    if ([value isKindOfClass:[NSDictionary class]]) {
    
    NSMutableDictionary *dict1 = [self dictShowAllFile:(NSDictionary*)value];
    [temp setObject:dict1 forKey:key];
      
    }else if([value isKindOfClass:[NSNumber class] ]){
        
    NSNumber  *num  = (NSNumber*) value;
    NSNumberFormatter *tempNum = [[NSNumberFormatter alloc] init];
    NSString*  valueStr = [tempNum stringFromNumber:num];
    [temp setObject:valueStr forKey:key];
    }else if([value isKindOfClass:[NSURL class] ]){
        NSURL *URL = (NSURL*) value;
       
        [temp setObject:URL.absoluteString?URL.absoluteString:@"" forKey:key];
    }else if ([value isKindOfClass:[NSString class]]) {
        
        [temp setObject:value forKey:key];
      
    }else if ([value isKindOfClass:[NSArray class]]) {
    
        [temp setObject:[self ayyayShowAllFile:(NSArray *)value] forKey:key];
       
    }

    }
    
    return temp;
}
+ (NSMutableArray*)ayyayShowAllFile:(NSArray *)dirArray
{
    NSMutableArray *newArray = [NSMutableArray array];
    for (NSObject * value in dirArray) {
        if ([value isKindOfClass:[NSDictionary class]]) {
        
        NSMutableDictionary *dict1 = [self dictShowAllFile:(NSDictionary*)value];
            [newArray addObject:dict1];
          
        }else if([value isKindOfClass:[NSNumber class] ]){
            
        NSNumber  *num  = (NSNumber*) value;
        NSNumberFormatter *tempNum = [[NSNumberFormatter alloc] init];
            
         NSString*  valueStr = [tempNum stringFromNumber:num];
            [newArray addObject:valueStr];
        }else if([value isKindOfClass:[NSURL class] ]){
            NSURL *URL = (NSURL*) value;
            [newArray addObject:URL.absoluteString?URL.absoluteString:@""];
           
        }else if ([value isKindOfClass:[NSString class]]) {
            [newArray addObject:value];
           
          
        }else if ([value isKindOfClass:[NSArray class]]) {
            NSMutableArray *new = [NSMutableArray array];
            
            for (NSObject*obj in (NSArray*)value) {
                if ([obj isKindOfClass:[NSDictionary class]]) {
                
                NSMutableDictionary *dict1 = [self dictShowAllFile:(NSDictionary*)obj];
                    [new addObject:dict1];
                  
                }else if([obj isKindOfClass:[NSNumber class] ]){
                    
                NSNumber  *num  = (NSNumber*) obj;
                NSNumberFormatter *tempNum = [[NSNumberFormatter alloc] init];
                    
                 NSString*  valueStr = [tempNum stringFromNumber:num];
                    [new addObject:valueStr];
                }else if([obj isKindOfClass:[NSURL class] ]){
                    NSURL *URL = (NSURL*) obj;
                    [new addObject:URL.absoluteString?URL.absoluteString:@""];
                   
                }else if ([obj isKindOfClass:[NSString class]]) {
                    [new addObject:obj];
                  
                }else if ([obj isKindOfClass:[NSArray class]]) {
                    
                    [new addObject:[self ayyayShowAllFile:(NSArray*)obj]];
                  
                }
            }
            
            [newArray addObject:new];
          
        }
    }
    return newArray;
}
//获取沙盒路径
+ (NSString *)stringWithDirectory:(TF_Directory)name
{
    NSString * directory;
    
    switch (name) {
        case TF_DirectoryDocuments: {
            directory = @"Documents";
            break;
        } case TF_DirectoryLibrary: {
            directory = @"Library/Caches/TalkfunCloudLive";
            break;
        } case TF_DirectoryTemp: {
            directory = @"tmp";
            break;
        }
        default:
            break;
    }
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:directory?directory:@""];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

+ (CGRect)getRectWithString:(NSString *)string size:(CGSize)size fontSize:(CGFloat)fontSize
{
    if ([string isKindOfClass:[NSString class]]) {
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
//        [style setLineBreakMode:NSLineBreakByWordWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName : style };
        
        CGRect frame = [string boundingRectWithSize:size options:opts attributes:attributes context:nil];
        CGRect rect = CGRectMake(frame.origin.x, frame.origin.y, ceil(frame.size.width), ceil(frame.size.height));
        return rect;
    }
    else
    {
        return CGRectZero;
    }
}

//根据提供的字符串、最大size和字符串字体大小获取CGRect(传入属性值)
+ (CGRect)getRectWithString:(NSString *)string size:(CGSize)size fontSize:(CGFloat)fontSize attributes:(nullable NSDictionary<NSString *, id> *)attributes
{
    if ([string isKindOfClass:[NSString class]]) {
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
//        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
//        [style setLineBreakMode:NSLineBreakByWordWrapping];
//
//        NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName : style };
        
        CGRect frame = [string boundingRectWithSize:size options:opts attributes:attributes context:nil];
        CGRect rect = CGRectMake(frame.origin.x, frame.origin.y, ceil(frame.size.width), ceil(frame.size.height));
        return rect;
    }
    else
    {
        return CGRectZero;
    }
}

//获取mac地址
+ (NSString *)getMacAddress
{
    return [[UIDevice currentDevice].identifierForVendor UUIDString];
}

- (NSString *)getUserNameAndTimeWith:(NSDictionary *)params
{
    NSString * userName  = params[@"nickname"];
    NSString * starttime = params[@"starttime"];
    NSInteger time       = [starttime integerValue];
    NSInteger hour       = time / 3600;
    NSInteger minutes    = (time - hour * 3600) / 60;
    NSInteger second     = time - minutes * 60 - hour * 3600;
    
    return [NSString stringWithFormat:@"%@:(%02ld:%02ld:%02ld)",userName,(long)hour,(long)minutes,(long)second];
}

//====================== 图文混排 =====================
+ (void)getImageRange:(NSString*)message :(NSMutableArray*)array {
    
    NSRange range = [message rangeOfString:BEGIN_FLAG];
    NSRange range1 = [message rangeOfString:END_FLAG];
    //判断当前字符串是否还有表情的标志。
    if (range.length > 0 && range1.length > 0) {
        if (range.location > 0) {
            if(message.length>range.location){
            [array addObject:[message substringToIndex:range.location]];
            [array addObject:[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)]];
            NSString * str = [message substringFromIndex:range1.location+1];
            [self getImageRange:str :array];
            }
           
        }else {
            NSString * nextstr = [message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)];
            //排除文字是“”的
            if (![nextstr isEqualToString:@""]) {
                [array addObject:nextstr];
                NSString * str = [message substringFromIndex:range1.location + 1];
                [self getImageRange:str :array];
            }else {
                return;
            }
        }
        
    }
    else if (message != nil) {
        [array addObject:message];
    }
    
}

+ (UIView *)assembleMessageAtIndex:(NSString *)message
{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    [TalkfunUtils getImageRange:message :array];
    UIView * returnView = [[UIView alloc] initWithFrame:CGRectZero];
    NSArray * data      = array;
    UIFont * fon        = [UIFont systemFontOfSize:13.0f];
    CGFloat upX         = 0;
    CGFloat upY         = 0;
    CGFloat X           = 0;
    CGFloat Y           = 0;
    if (data) {
        for (int i = 0;i < [data count]; i++) {
            NSString * str = [data objectAtIndex:i];
            if ([str hasPrefix:BEGIN_FLAG] && [str hasSuffix:END_FLAG])
            {
                if (upX >= MAX_WIDTH)
                {
                    upY = upY + KFacialSizeHeight;
                    upX = 0;
                    X   = 150;
                    Y   = upY;
                }
                
                NSString * imageName = [str substringWithRange:NSMakeRange(1, str.length - 2)];
                UIImageView * img    = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
                img.frame            = CGRectMake(upX, upY, KFacialSizeWidth, KFacialSizeHeight);
                [returnView addSubview:img];
                upX                  = KFacialSizeWidth+upX;
                if (X < 150) X = upX;
                
                
            } else {
                for (int j = 0; j < [str length]; j++) {
                    NSString * temp = [str substringWithRange:NSMakeRange(j, 1)];
                    if (upX >= MAX_WIDTH)
                    {
                        upY = upY + KFacialSizeHeight;
                        upX = 0;
                        X   = 150;
                        Y   = upY;
                    }
                    CGRect rect        = [temp boundingRectWithSize:CGSizeMake(150, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
                    //                    CGSize size = [temp sizeWithFont:fon constrainedToSize:CGSizeMake(150, 40)];
                    UILabel * la       = [[UILabel alloc] initWithFrame:CGRectMake(upX,upY,rect.size.width,rect.size.height)];
                    la.font            = fon;
                    la.text            = temp;
                    la.textAlignment   = NSTextAlignmentCenter;
                    la.backgroundColor = [UIColor clearColor];
                    [returnView addSubview:la];
                    upX                = upX + rect.size.width;
                    if (X < 150) {
                        X = upX;
                    }
                }
            }
        }
    }
    
    returnView.frame = CGRectMake(2.0f, 2.0f, X, Y); //@ 需要将该view的尺寸记下，方便以后使用
    
    return returnView;
}

+ (NSDictionary *)assembleAttributeString:(NSString *)string boundingSize:(CGSize)size fontSize:(CGFloat)fontSize shadow:(BOOL)containShadow
{
    if (!string || ![string isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    NSDictionary *expressionDict = [self getExpressionDict];
    
    NSDictionary * bigExpressionDict = [self getBigExpressionDict];
    //下面这些是过期的大的表情, 不要了
//  NSDictionary * bigExpressionDict = @{@"[love1]":@"[爱你么么哒]",
//                                         @"[talkWell]":@"[讲得好]",
//                                         @"[great]":@"[老师好棒哦]",
//                                         @"[happy]":@"[好开心]",
//                                         @"[Fireworks]":@"[送你花]",
//                                         @"[smart]":@"[机智的我]",
//                                         @"[bye]":@"[拜拜啦]",
//                                         @"[study]":@"[天天向上]",
//                                         @"[hello]":@"[大家好]",
//                                         @"[coming]":@"[我来啦]"
//                                         };

    
    
    @synchronized (self) {
        
        for (NSString * name in expressionDict) {
            string = [string stringByReplacingOccurrencesOfString:name withString:expressionDict[name]];
        }
        for (NSString * name in bigExpressionDict) {
            string = [string stringByReplacingOccurrencesOfString:name withString:bigExpressionDict[name]];
        }
        NSShadow * shadow = [[NSShadow alloc] init];
        if (containShadow) {
            shadow.shadowOffset = CGSizeMake(0.5, 0.5);
            shadow.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        }
        
        CGFloat forgottenLength = 0;
        NSMutableAttributedString * originalAttributedString = [NSMutableAttributedString new];
        NSArray * leftArr = [string componentsSeparatedByString:@"["];
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",leftArr.firstObject] attributes:@{NSShadowAttributeName:shadow}];
        
        //先拼接一开始的那个
        [originalAttributedString appendAttributedString:attrStr];
        
        for (int i = 1; i < leftArr.count; i ++) {
            NSArray * leftRightArr = [leftArr[i] componentsSeparatedByString:@"]"];
            NSString * imageName = leftRightArr[0];
            if (imageName ) {

            }
      

            
            UIImage * image = [UIImage imageNamed:imageName];
            if (image) {
                // 添加表情
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                // 表情图片
                attch.image = image;
                CGFloat width = 20;
//                if ([bigExpressionDict.allValues containsObject:[NSString stringWithFormat:@"[%@]",imageName]]) {
//                    width = 60;
//
//                    // 设置图片大小
//                    attch.bounds = CGRectMake(0,  -47, width, width);
//                }else{
                    // 设置图片大小
                    attch.bounds = CGRectMake(0, -5, width, width);
//                }
               
                
                NSAttributedString *attchStr = [NSAttributedString attributedStringWithAttachment:attch];
                
                //第一次拼接
                [originalAttributedString appendAttributedString:attchStr];
                
                //计算少了多少长度
                forgottenLength += 3;
            }
            else
            {
                //第一次拼接
                NSAttributedString * firstStr = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"[%@]",leftRightArr.firstObject]];
                [originalAttributedString appendAttributedString:firstStr];
            }
            
            NSAttributedString * secondStr = [[NSAttributedString alloc] initWithString:leftRightArr.lastObject attributes:@{NSShadowAttributeName:shadow}];
            
            //如果有多个"]"
            if (leftRightArr.count > 2) {
                NSMutableArray * arr = [NSMutableArray arrayWithArray:leftRightArr];
                [arr removeObjectAtIndex:0];
                secondStr = [[NSAttributedString alloc] initWithString:[arr componentsJoinedByString:@"]"]];
            }
            
            //第二次拼接
            [originalAttributedString appendAttributedString:secondStr];
            
        }
        [originalAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:NSMakeRange(0, [originalAttributedString string].length)];
        
        NSMutableString * str = [[NSMutableString alloc] initWithString:[originalAttributedString string]];
        
        for (int i = 0; i < forgottenLength; i ++) {
            [str appendString:@"a"];
        }
        
        CGRect rect = [TalkfunUtils getRectWithString:str size:CGSizeMake(size.width, size.height) fontSize:fontSize];
        
        
        NSString * rectStr = NSStringFromCGRect(rect);
        
        return @{AttributeStr:originalAttributedString,TextRect:rectStr};
    }
    
}

static CGFloat ExtraHeight = 60-13;
+ (CGFloat)getExtraHeightWithString:(NSString *)string fontSize:(CGFloat)fontSize boundingSize:(CGSize)size row:(NSInteger)row
{

    NSDictionary * bigExpressionDict = [self getBigExpressionDict];
    NSArray * strsArray = [self getSeparatedLinesFromtext:string font:[UIFont systemFontOfSize:fontSize] maxWidth:size.width];
    
    CGFloat extraHeight = 0;
    for (int i = 0; i < strsArray.count; i ++) {
        if (strsArray.count > i) {
            NSString * followStr;
            if (i+1 < strsArray.count) {
                followStr = strsArray[i+1];
            }
            NSString * str = strsArray[i];
            BOOL contain = NO;
            for (NSString * key in bigExpressionDict.allKeys) {
                NSString * newStr = [[key stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""];
                if ([str containsString:newStr]) {
                    extraHeight += ExtraHeight;
                    contain = YES;
                    break;
                }
            }
            if (!contain && followStr && [followStr containsString:@"]"]) {
                NSArray * strComponents = [str componentsSeparatedByString:@"["];
                NSArray * followComponents = [followStr componentsSeparatedByString:@"]"];
                if (strComponents.count != 1 && followComponents.count != 1) {
                    NSString * lastComponent = strComponents.lastObject;
                    NSString * firstComponent = followComponents.firstObject;
                    for (NSString * key in bigExpressionDict.allKeys) {
                        if ([key containsString:lastComponent] && [key containsString:firstComponent]) {
                            extraHeight += ExtraHeight;
                            break;
                        }
                    }
                }
            }
        }
    }
    
    return extraHeight;
}

/**
 *  获取每行的文字
 *
 *  @param text     文本内容
 *  @param font     字体
 *  @param maxWidth 容器的最大宽度
 *
 *  @return 存储每行文字的数组
 */

+ (NSArray *)getSeparatedLinesFromtext:(NSString *)text font:(UIFont *)font maxWidth:(CGFloat)maxWidth
{
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,maxWidth,100000));
    
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
   
    
    
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    
    for (id line in lines)
    {
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        
        NSString *lineString = [text substringWithRange:range];
        [linesArray addObject:lineString];
    }
    
    CFRelease(myFont);
    CFRelease(path);
    CFRelease(frameSetter);
    CFRelease(frame);
    return (NSArray *)linesArray;
}

//计算出大小
+ (NSString *)fileSizeWithInterge:(NSInteger)size
{
    // 1k = 1024, 1m = 1024k
    if (size < 1024) {// 小于1k
        return [NSString stringWithFormat:@"%ldB",(long)size];
    }else if (size < 1024 * 1024){// 小于1m
        CGFloat aFloat = size/1024;
        return [NSString stringWithFormat:@"%.0fK",aFloat];
    }else if (size < 1024 * 1024 * 1024){// 小于1G
        CGFloat aFloat = size/(1024 * 1024);
        return [NSString stringWithFormat:@"%.1fM",aFloat];
    }else{
        CGFloat aFloat = size/(1024*1024*1024);
        return [NSString stringWithFormat:@"%.1fG",aFloat];
    }
}

+ (CGRect)estimateFrame:(CGRect)containerFrame imageViewFrame:(CGRect)imageViewFrame
{
    CGRect rect = imageViewFrame;
    
    CGFloat width = rect.size.height * (4 / 3.0);
    CGFloat distant;
    
    //如果容器的高度的4 / 3 大于它的宽度（贴着容器上下边）
    if (width > rect.size.width) {
        CGFloat height = rect.size.width * (3 / 4.0);
        distant = height - rect.size.height;
        
        return CGRectMake(0, 0 - distant / 2, rect.size.width, height);
        
    }
    //贴着容器左右边
    else
    {
        distant = width - rect.size.width;
        return CGRectMake(- distant / 2, 0, width, rect.size.height);
    }
}

+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    
    return img;
}

+ (UIImage*)imageWithImage:(UIImage*)image
{
    CGSize imageSize = image.size;
    if (imageSize.height <= 1280 && imageSize.width <= 1280) {
        return image;
    }
    CGSize newSize = CGSizeZero;
    if (imageSize.height > imageSize.width) {
        newSize.height = 1280;
        newSize.width = imageSize.width / (imageSize.height / 1280);
    }
    else
    {
        newSize.width = 1280;
        newSize.height = imageSize.height / (imageSize.width / 1280);
    }
    
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

//获取图片大小
+ (CGFloat)getSize:(UIImage *)image
{
    int  perMBBytes = 1024*1024;
    
    CGImageRef cgimage = image.CGImage;
    size_t bpp = CGImageGetBitsPerPixel(cgimage);
    size_t bpc = CGImageGetBitsPerComponent(cgimage);
    size_t bytes_per_pixel = bpp / bpc;
    
    CGFloat lPixelsPerMB  = perMBBytes / bytes_per_pixel * 1.0;
    
    
    long totalPixel = CGImageGetWidth(image.CGImage) * CGImageGetHeight(image.CGImage);
    
    
    CGFloat totalFileMB = totalPixel / lPixelsPerMB / 1.0;
    
    return totalFileMB;
}



+ (TalkfunUtils*)shared {
    if(!_counter){
        _counter = [[self alloc] init];
    }
    return _counter;
}
+ (void)load
{
    // 回到主线程更新UI
//    dispatch_async(dispatch_get_main_queue(), ^{
      TalkfunUtils *utils =  [TalkfunUtils shared];
    if (utils.wkWebView==nil) {
        utils.wkWebView =   [[WKWebView alloc] initWithFrame:CGRectZero];
    }
     __block BOOL finished = NO;
        [utils.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            
       
            if ([result isKindOfClass:[NSString class]]) {
                utils.user_Agent  = result;
            }else{
                utils.user_Agent = @"Mozilla/5.0 (iPhone; CPU iPhone OS 12_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148";
            }
           
            finished = YES;
//             NSLog(@"utils.user_Agent===>%@",utils.user_Agent);
            
            if (![result containsString:@"Talkfun-iOS-CloudLive"]) {
                NSString *identifier = [[NSBundle mainBundle] bundleIdentifier];
                NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//                 TalkfunCloudLiveSDKVersion
                utils.user_Agent = [utils.user_Agent stringByAppendingFormat:@" Talkfun-iOS-CloudLive/%@ %@/%@",@"2.3.0",identifier,appVersion];
            }
        }];
    while (finished == NO)
        
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
//    });
}
//获取userAgent
-(NSString *)getUserAgent{
//   NSLog(@"111===>%@",_user_Agent);
    return _user_Agent;
}

//获取头像urlString
+ (nullable NSString *)getAvatarString:(nonnull NSString *)xid avatarHost:(nonnull NSString *)avatarHost{
    //    MT.room.ext.avatarHost+'/avatar/'+(packet.args.xid%255)+'/'+(packet.args.xid%600)+'/'+(packet.args.xid%1024)+'/'+packet.args.xid+'.jpg';
    //if (data[@"ext"] && data[@"ext"][@"avatarHost"]) {
    NSInteger xidInt = [xid integerValue];
    return [NSString stringWithFormat:@"%@/avatar/%ld/%ld/%ld/%@.jpg",avatarHost,xidInt%255,xidInt%600,xidInt%1024,xid];
    //}
    return nil;
}

+ (BOOL)mkdirs:(NSString *)directory
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {

        NSString *parentDirectory = [directory stringByDeletingLastPathComponent];
        
        [TalkfunUtils mkdirs:parentDirectory];
        
        NSError *error = nil;
        BOOL result =  [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error];
        return result;
    }
    
    return YES;
}

+ (BOOL)archivedToFile:(NSString *)file data:(id)data {
    NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:data];
    return [imageData writeToFile:file atomically:YES];
}

+(NSMutableArray*)getArray
{
    NSArray *array1 =  @[@"[hard]",@"[aha]",@"[why]",@"[Fireworks]",@"[pitiful]",@"[amaz]",@"[good]",@"[cool]",@"[bye]",@"[rose]"];
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:array1];
    NSArray * arr1 = @[@"[slime]",@"[laugh]",@"[love]",@"[tongue]",@"[daze]",@"[handclap]",@"[titter]",@"[handssors]",@"[six]",@"[heart]",@"[melon]",@"[silly]",@"[dog]",@"[like]",@"[expect]",@"[666]",@"[flower]",@"[proud]"];
    [array addObjectsFromArray:arr1];
    
    return array;
}

//新的表情包
+(NSDictionary*)getNewExpressionDict
{

    return @{@"[hello]":@"TF_hello",
             @"[coming]":@"TF_coming",
             @"[study]":@"TF_study",
             @"[smart]":@"TF_smart",
             @"[know]":@"TF_know",
             @"[flower]":@"TF_flower",
             @"[happy]":@"TF_happy",
             @"[talkwell]":@"TF_talkwell",
             @"[great]":@"TF_great",
             @"[love]":@"TF_love",
             @"[bye]":@"TF_bye"
           
    };
}

+(NSMutableDictionary*)getExpressionDict
{

//    NSMutableArray *array = [self getArray];
//
//    for (int  i = 16; i<35; i++) {
//
//        [array addObject:[NSString stringWithFormat:@"[emoticon%i]",i+1]];
//
//    }

    NSDictionary *expressionDict1 = @{@"[fd]":@"[hard]",
                                     @"[lg]":@"[aha]",
                                     @"[qu]":@"[why]",
                                     @"[fl]":@"[Fireworks]",
                                     @"[kl]":@"[pitiful]",
                                     @"[jy]":@"[amaz]",
                                     @"[gz]":@"[good]",
                                     @"[hx]":@"[cool]",
                                     @"[tx]":@"[love]",
                                     @"[ag]":@"[bye]",
                                     @"[S_FLOWER]":@"[rose]"};
    
    
    NSMutableDictionary *expressionDict = [NSMutableDictionary dictionaryWithDictionary:expressionDict1];
    
    return expressionDict;
}

+(NSDictionary*)getBigExpressionDict

{
    return @{@"[slime]":@"[slime]",
             @"[laugh]":@"[laugh]",
             @"[love]":@"[love]",
             @"[tongue]":@"[tongue]",
             @"[daze]":@"[daze]",
             @"[handclap]":@"[handclap]",
             @"[titter]":@"[titter]",
             @"[handssors]":@"[handssors]",
             @"[six]":@"[six]",
             @"[heart]":@"[heart]",
             @"[melon]":@"[melon]",
             @"[silly]":@"[silly]",
             @"[dog]":@"[dog]",
             @"[like]":@"[like]",
             @"[expect]":@"[expect]",
             @"[flower]":@"[flower]",
             @"[色]":@"[emoticon17]",
             @"[调皮]":@"[emoticon18]",
             @"[害羞]":@"[emoticon19]",
             @"[奸笑]":@"[emoticon20]",
             @"[尴尬]":@"[emoticon21]",
             @"[惊讶]":@"[emoticon22]",
             @"[闭嘴]":@"[emoticon23]",
             @"[呲牙]":@"[emoticon24]",
             @"[大哭]":@"[emoticon25]",
            
             @"[囧]":@"[emoticon26]",
             @"[难过]":@"[emoticon27]",
             @"[敲打]":@"[emoticon28]",
             @"[委屈]":@"[emoticon29]",
             @"[疑问]":@"[emoticon30]",
             @"[郁闷]":@"[emoticon31]",
             @"[再见]":@"[emoticon32]",
             @"[可怜]":@"[emoticon33]",
             @"[捂脸]":@"[emoticon34]",
             @"[笑哭]":@"[emoticon35]",
             @"[安慰]":@"[emoticon26]",
             @"[666]":@"[six]",
};
}



//生成图文富文本
+ (NSMutableAttributedString*_Nonnull)new_getAttributedText:(NSString *)str fontSize:(UIFont*)font foregroundColor:(UIColor*)color
{
    NSDictionary *attrs = @{NSFontAttributeName : font };
    CGSize attrsSize = [@"计算高度" sizeWithAttributes:attrs];
    
    
    NSMutableDictionary *expressionDict = [self getExpressionDict];
    NSDictionary *expressionDict2 = [self getBigExpressionDict];
    for (int i = 0; i < expressionDict2.count; ++i) {
    //  获取字典中所有的key
     NSArray *keys = [expressionDict2 allKeys];
    //  取出当前位置对应的key
     
     NSString *key = keys[i];
     NSString *value = expressionDict2[key];
        [expressionDict setObject:value forKey:key];

     }
    
    
        //将字符串中" name" 全部替换成 expressionDict[name]
    //   str = [str stringByReplacingOccurrencesOfString :@"name " withString:expressionDict[name]"];
    
    //例如:找到聊天内容的 "[fd]"换成 @"[hard]"
    for (NSString * name in expressionDict) {
        str = [str stringByReplacingOccurrencesOfString:name withString:expressionDict[name]];
    }
    
   
    //1.图文混排
    NSMutableAttributedString *String = [[NSMutableAttributedString alloc] init];
    
    //{
//        "index" : 0,
//        "subStr" : "[aha]"
//    }
    NSMutableArray*subStrArray = [TalkfunUtils completeStr:str splitArray:[self getArray]];
    //    NSLog(@"排序后的字典%@",subStrArray);
    
    NSString *splitter = @"(欢拓分割符号)";
    
    //占位替换
    for (NSDictionary *dict  in subStrArray) {
        //替换 "[aha]" 为 @"(欢拓分割符号)"
        str = [str stringByReplacingOccurrencesOfString :dict[@"subStr"] withString:splitter];
    }

    
    //分割数据
    NSArray * nameArray = [str componentsSeparatedByString:splitter];
    
    //找出所有字符串
    for (int i = 0; i<nameArray.count; i++)
    {
        
        NSString *key =  nameArray[i];
       
        if ([key isKindOfClass:[NSString class]])
        {
            
            
            //拿到整体的字符串
            NSMutableAttributedString *name = [[NSMutableAttributedString alloc] initWithString:key];
            
            // 设置 name 颜色，也可以设置字体大小等
            [name addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, name.length)];
            
            
            [name addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, name.length)];
            
            [String appendAttributedString:name];
            
            
            if (i < subStrArray.count) {
                NSDictionary *dict =    subStrArray[i];
                
                // 创建图片图片附件
                NSTextAttachment *attach = [[NSTextAttachment alloc] init];
                
                NSString*name5 = dict[@"subStr"];
                
                //替换 "[3]" 为 @"(欢拓分割符号)"
                name5 = [name5 stringByReplacingOccurrencesOfString :@"[" withString:@""];
                
                name5 = [name5 stringByReplacingOccurrencesOfString :@"]" withString:@""];
                
                
                attach.image = [UIImage imageNamed:name5];
                attach.bounds = CGRectMake(0, 0, attrsSize.height, attrsSize.height);
                attach.bounds = CGRectMake(0, round(font.capHeight - attrsSize.height)/2.0, attrsSize.height, attrsSize.height);

                NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
                
                //将图片插入到合适的位置
                [String insertAttributedString:attachString atIndex:String.length];
            }

        }
        
    }
    
    
    return String;
    
}


//生成图文富文本
+ (NSMutableAttributedString * __nonnull)getAttributedText:(NSString *)str fontSize:(UIFont*)font foregroundColor:(UIColor*)color
{

    NSMutableDictionary *expressionDict = [self getExpressionDict];
    NSDictionary *expressionDict2 = [self getBigExpressionDict];
    for (int i = 0; i < expressionDict2.count; ++i) {
    //  获取字典中所有的key
     NSArray *keys = [expressionDict2 allKeys];
    //  取出当前位置对应的key
     
     NSString *key = keys[i];
     NSString *value = expressionDict2[key];
        [expressionDict setObject:value forKey:key];

     }
    
    
        //将字符串中" name" 全部替换成 expressionDict[name]
    //   str = [str stringByReplacingOccurrencesOfString :@"name " withString:expressionDict[name]"];
    
    //例如:找到聊天内容的 "[fd]"换成 @"[hard]"
    for (NSString * name in expressionDict) {
        str = [str stringByReplacingOccurrencesOfString:name withString:expressionDict[name]];
    }
    
   
    //1.图文混排
    NSMutableAttributedString *String = [[NSMutableAttributedString alloc] init];
    
    //{
//        "index" : 0,
//        "subStr" : "[aha]"
//    }
    NSMutableArray*subStrArray = [TalkfunUtils completeStr:str splitArray:[self getArray]];
    //    NSLog(@"排序后的字典%@",subStrArray);
    
    NSString *splitter = @"(欢拓分割符号)";
    
    //占位替换
    for (NSDictionary *dict  in subStrArray) {
        //替换 "[aha]" 为 @"(欢拓分割符号)"
        str = [str stringByReplacingOccurrencesOfString :dict[@"subStr"] withString:splitter];
    }

    
    //分割数据
    NSArray * nameArray = [str componentsSeparatedByString:splitter];
    
    //找出所有字符串
    for (int i = 0; i<nameArray.count; i++)
    {
        
        NSString *key =  nameArray[i];
       
        if ([key isKindOfClass:[NSString class]])
        {
            
            
            //拿到整体的字符串
            NSMutableAttributedString *name = [[NSMutableAttributedString alloc] initWithString:key];
            
            // 设置 name 颜色，也可以设置字体大小等
            [name addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, name.length)];
            
            
            [name addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, name.length)];
            
            [String appendAttributedString:name];
            
            
            if (i < subStrArray.count) {
                NSDictionary *dict =    subStrArray[i];
                
                // 创建图片图片附件
                NSTextAttachment *attach = [[NSTextAttachment alloc] init];
                
                NSString*name5 = dict[@"subStr"];
                
                //替换 "[3]" 为 @"(欢拓分割符号)"
                name5 = [name5 stringByReplacingOccurrencesOfString :@"[" withString:@""];
                
                name5 = [name5 stringByReplacingOccurrencesOfString :@"]" withString:@""];
                
                
                attach.image = [UIImage imageNamed:name5];
                attach.bounds = CGRectMake(0, -5 , 22, 22);
                
                NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
                
                //将图片插入到合适的位置
                [String insertAttributedString:attachString atIndex:String.length];
            }
            
            
            
            
        }
        
    }
    
    
    return String;
    
}

+ (NSMutableArray*_Nullable)completeStr:(NSString*_Nullable)completeStr   splitArray:(NSArray*_Nonnull)array
{
    
    //所有表情的位置与内容
    NSMutableArray *subStrArray = [NSMutableArray array];
    
    for (NSString * name  in array) {
        //单位表情的位置与内容
        NSMutableArray* subStr  =    [self getDuplicateSubStrLocInCompleteStr:completeStr withSubStr:name];
        
        [subStrArray addObjectsFromArray:subStr];
    }
    
    
    
    
    NSMutableArray *indexArray  = [NSMutableArray array];
    
    for (NSDictionary *dict  in subStrArray) {
        NSNumber  *index = dict[@"index"];
        [indexArray addObject:index];
    }
    
    
    //从小到大排序
    NSArray * sortedArr = [indexArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        return [obj1 compare:obj2];
        
    }];
    
    
    
    
    NSMutableArray *new = [NSMutableArray array];
    //字典排序
    for (NSNumber  *index in sortedArr) {
        
        
        for (NSDictionary *dict in subStrArray) {
            if ([index isEqualToNumber:dict[@"index"]]) {
                [new addObject:dict];
            }
            
        }
        
        
        
    }
    
    return new;
}

/**
 *  返回UILabel自适应后的size
 *
 *  @param aString 字符串
 *  @param width   指定宽度
 *
 *  @return CGSize
 */
+ (CGSize)sizeLabelToFit:(NSAttributedString *_Nonnull)aString width:(CGFloat)width fontSize:(UIFont*_Nullable)font{
    
    if ([TalkfunUtils shared].sizeLabel == nil) {
        [TalkfunUtils shared].sizeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
    }
    UILabel *tempLabel = [TalkfunUtils shared].sizeLabel;
    tempLabel.frame = CGRectMake(0, 0, width, 0);
    tempLabel.font = font;
    tempLabel.attributedText = aString;
    tempLabel.numberOfLines = 0;

    [tempLabel sizeToFit];
    CGSize size = tempLabel.frame.size;
    tempLabel.lineBreakMode = NSLineBreakByCharWrapping;
    
    

    return size;
}
//利用切分先得数组,再根据索引计算
+ (NSMutableArray *)getDuplicateSubStrLocInCompleteStr:(NSString *)completeStr withSubStr:(NSString *)subStr
{
    NSArray * separatedStrArr = [completeStr componentsSeparatedByString:subStr];
    NSMutableArray * locMuArr = [[NSMutableArray alloc]init];
    
    NSInteger index = 0;
    for (NSInteger i = 0; i<separatedStrArr.count-1; i++) {
        NSString * separatedStr = separatedStrArr[i];
        index = index + separatedStr.length;
        NSNumber * loc_num = [NSNumber numberWithInteger:index];
        
        //表情所在位置与表情
        
        NSDictionary * dict =  @{
                                 @"index":loc_num,
                                 @"subStr":subStr
                                 };
        
        [locMuArr addObject:dict];
        index = index+subStr.length;
    }
    return locMuArr;
}

/**
 检测输入的手机号是否正确
 */
+ (NSString *_Nullable)valiMobile:(NSString *_Nullable)mobile
{
    if (mobile.length != 11) {
        return @"手机号长度只能是11位";
    } else {
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(17[0-9])|(18[2-4,7-8]))\\d{8}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        } else {
//            return @"请输入正确的电话号码";
            return nil;
        }
    }
    return nil;
}

//获取某个字符串或者汉字的首字母.

//+ (NSString *_Nullable)firstCharactorWithString:(NSString *_Nullable)string
//
//{
//    NSMutableString *str = [NSMutableString stringWithString:string];
//
//    CFStringTransform((CFMutableStringRef) str, NULL, kCFStringTransformMandarinLatin, NO);
//
//    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
//
//    NSString *pinYin = [str capitalizedString];
//
//    return [pinYin substringToIndex:1];
//
//}

+(id  )getJsonDataJsonname:(NSString *_Nullable)jsonname
{
    NSString *path = [[NSBundle mainBundle] pathForResource:jsonname?jsonname:@"" ofType:@"json"];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];
    if (jsonData) {
    NSError *error;
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData?jsonData:[[NSData alloc]init] options:NSJSONReadingMutableContainers error:&error];
    if (!jsonObj || error) {
        //DLog(@"JSON解码失败");

        return @{};

    } else {
        return jsonObj;
    }
    }else
    {
        return @{};
    }
    
}
+(CGRect)getMainScreen
{
CGFloat superViewW = [UIScreen mainScreen].bounds.size.width;
CGFloat superViewH = [UIScreen mainScreen].bounds.size.height;
    
//1 ==螢幕直立

if ([UIDevice currentDevice].orientation==1 && superViewH< superViewW) {
        superViewH =  [UIScreen mainScreen].bounds.size.width;
        superViewW =  [UIScreen mainScreen].bounds.size.height ;
}
    
return CGRectMake(0, 0, superViewW, superViewH);

}


//判断是否输入的是url
+(BOOL)isWhetherNoUrl:(NSString *)urlStr
{
    if(urlStr == nil) {
        return NO;
    }
    NSString *url;
    if (urlStr.length>4 && [[urlStr substringToIndex:4] isEqualToString:@"www."]) {
        url = [NSString stringWithFormat:@"http://%@",self];
    }else{
        url = urlStr;
    }
    NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    NSPredicate* urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    return [urlTest evaluateWithObject:url];
}

//提取url
+(NSArray*)getURLFromStr:(NSString *)string
{
    NSError *error;
      //可以识别url的正则表达式
      NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";

      NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
      options:NSRegularExpressionCaseInsensitive
      error:&error];

      NSArray *arrayOfAllMatches = [regex matchesInString:string
      options:0
      range:NSMakeRange(0, [string length])];

      //NSString *subStr;
      NSMutableArray *arr=[[NSMutableArray alloc] init];

      for (NSTextCheckingResult *match in arrayOfAllMatches){
          NSString* substringForMatch;
          substringForMatch = [string substringWithRange:match.range];
          [arr addObject:substringForMatch];
      }
      return arr;
}
+ (NSAttributedString*)getInternalFontOfSiz:(CGFloat)size withMsg:(NSString*)msg
{
    NSString *aa = msg;
    NSDictionary *attrs = @{NSFontAttributeName : [TalkfunUtils getFont: size]};
    CGSize attrsSize = [aa sizeWithAttributes:attrs];

    UILabel *aaL = [UILabel new];
    aaL.frame = CGRectMake(0, 0, attrsSize.width, attrsSize.height);
    aaL.text = aa;
    aaL.font = [TalkfunUtils getFont: size-2];
    aaL.textColor = [UIColor whiteColor] ;
    if ([msg rangeOfString:@"内部"].location != NSNotFound ) {
        aaL.backgroundColor = internalBackgroundColor;
    }else if ([msg rangeOfString:@"虚拟用户"].location != NSNotFound ) {
        aaL.backgroundColor = [UIColor colorWithRed:23/255.0 green:145/255.0 blue:251/255.0 alpha:1.0];
    }
    aaL.clipsToBounds = YES;
    aaL.layer.cornerRadius = 2;
    aaL.textAlignment = NSTextAlignmentCenter;

    //调用方法，转化成Image
    UIImage *image = [self imageWithUIView:aaL];
    //创建Image的富文本格式
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.bounds = CGRectMake(0,- (aaL.bounds.size.height/4), aaL.bounds.size.width, aaL.bounds.size.height); //这个-2.5是为了调整下标签跟文字的位置
    attach.image = image;
    //添加到富文本对象里
    NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:attach];
    return imageStr;
}
//view转成image
+ (UIImage*)imageWithUIView:(UIView*) view{

    UIImage *imageRet = [[UIImage alloc]init];
    //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度);
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageRet;
}
+ (BOOL)isDesignatedPartner:(NSString*)partner_id
{
    BOOL isDesignatedPartner= NO;
    NSArray *array = @[@"13852",@"12268",@"11306",@"20",@"38089",@"39131"];
    for (NSString *str in array) {
        if ([partner_id?partner_id:@"" isEqualToString:str]) {
            isDesignatedPartner = YES;
       }
    }
    return isDesignatedPartner;
}
+ (UIFont*)getFont:(CGFloat)size
{
//    return  [TalkfunUtils getFont: size];
    return  [UIFont systemFontOfSize:size];
}


//压缩图片大小

+ (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    maxLength*=1024;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    NSData *data11 = UIImageJPEGRepresentation(resultImage, compression);
    NSLog(@"adt1==%ld",data11.length);
    return resultImage;
}

+(NSString*)getNewNumber:(NSObject*)obj
{
    NSString *UsersXid = @"0";
    
    if([obj isKindOfClass:[NSNumber class] ]){
        
        NSNumber  *num     = (NSNumber*) obj;
        NSNumberFormatter *tempNum = [[NSNumberFormatter alloc] init];
        
        UsersXid = [tempNum stringFromNumber:num];
    }else if([obj isKindOfClass:[NSString class] ]){
        
        NSString  *str    = (NSString*)obj;
        UsersXid = str;
    }
    
    return UsersXid;
}



@end
